/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Despinches;
import com.camachosanchez.bean.DetalleDespinche;
import com.camachosanchez.bean.Neumaticos;
import com.camachosanchez.reportes.ReporteDespinches;
import com.camachosanchez.reportes.bean.HistorialDespinches;
import com.camachosanchez.reportes.bean.HistorialDespinchesDetalle;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.swing.JOptionPane;

/**
 *
 * @author ZULLY
 */
public class DialogoReporteDespinches extends javax.swing.JDialog {

    /**
     * Creates new form DialogoReporteDespinches
     */
    public DialogoReporteDespinches(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setSize(360, 154);
        setResizable(false);
        setLocationRelativeTo(null);
        dateDesde.setDate(new Date());
        dateHasta.setDate(new Date());
        GUIUtil.addEscapeKey(this);
        txtCodigo.setEditable(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        dateDesde = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        dateHasta = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        radBtnTodos = new javax.swing.JRadioButton();
        radBtnEspecifico = new javax.swing.JRadioButton();
        jToolBar1 = new javax.swing.JToolBar();
        jPanel5 = new javax.swing.JPanel();
        btnDespinches = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Reporte de despinches ::.");

        jPanel3.setBackground(new java.awt.Color(231, 239, 247));
        jPanel3.setPreferredSize(new java.awt.Dimension(407, 24));

        jLabel2.setText("Desde:");
        jLabel2.setPreferredSize(new java.awt.Dimension(40, 20));

        dateDesde.setDateFormatString("dd/MM/yyyy");
        dateDesde.setMaxSelectableDate(new Date());
        dateDesde.setPreferredSize(new java.awt.Dimension(120, 20));
        dateDesde.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateDesdePropertyChange(evt);
            }
        });

        jLabel3.setText("Hasta:");
        jLabel3.setMaximumSize(new java.awt.Dimension(38, 14));
        jLabel3.setMinimumSize(new java.awt.Dimension(38, 14));
        jLabel3.setPreferredSize(new java.awt.Dimension(38, 14));

        dateHasta.setDateFormatString("dd/MM/yyyy");
        dateHasta.setMaxSelectableDate(new Date());
        dateHasta.setPreferredSize(new java.awt.Dimension(120, 20));

        jLabel1.setText("Código:");

        buttonGroup1.add(radBtnTodos);
        radBtnTodos.setSelected(true);
        radBtnTodos.setText("Todos los neumáticos");
        radBtnTodos.setOpaque(false);
        radBtnTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radBtnTodosActionPerformed(evt);
            }
        });

        buttonGroup1.add(radBtnEspecifico);
        radBtnEspecifico.setText("Neumático específico");
        radBtnEspecifico.setOpaque(false);
        radBtnEspecifico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radBtnEspecificoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(dateDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(dateHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(radBtnEspecifico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(radBtnTodos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(10, Short.MAX_VALUE))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dateHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(radBtnTodos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(radBtnEspecifico, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(122, 122, 122))
        );

        getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setMinimumSize(new java.awt.Dimension(73, 30));
        jToolBar1.setPreferredSize(new java.awt.Dimension(73, 30));

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));

        btnDespinches.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/pdf.png"))); // NOI18N
        btnDespinches.setText("Imprimir");
        btnDespinches.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnDespinches.setContentAreaFilled(false);
        btnDespinches.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDespinchesActionPerformed(evt);
            }
        });
        jPanel5.add(btnDespinches);

        jToolBar1.add(jPanel5);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private List<Despinches> getDatos(Neumaticos neumatico, Date fechaIni, Date fechaFin) {
        EntityManagerFactory emf = JPAUtil.getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        java.sql.Date sqlFechaIni = new java.sql.Date(fechaIni.getTime());
        java.sql.Date sqlFechaFin = new java.sql.Date(fechaFin.getTime());
        Query q1 = em.createQuery("SELECT D FROM Despinches D "
                + "WHERE D.fecha <= :fechaFin AND D.fecha >= :fechaIni "
                + ((neumatico == null) ? "" : "AND D.idNeumaticos.id = :idNeumtico ")
                + "ORDER BY D.idNeumaticos.codigo, D.fecha");
        q1.setParameter("fechaIni", sqlFechaIni);
        q1.setParameter("fechaFin", sqlFechaFin);
        if (neumatico != null) {
            q1.setParameter("idNeumtico", neumatico.getId());
        }
        return q1.getResultList();
    }

    private void btnDespinchesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDespinchesActionPerformed
        // TODO add your handling code here:
        HistorialDespinches historial = new HistorialDespinches();
        historial.setFechaDesde(GUIUtil.convertirFechaDDMMYYY(dateDesde.getDate()));
        historial.setFechaHasta(GUIUtil.convertirFechaDDMMYYY(dateHasta.getDate()));
        List<HistorialDespinchesDetalle> detallesHistorial = new ArrayList<HistorialDespinchesDetalle>();
        if (radBtnTodos.isSelected()) {
            List<Despinches> datos = getDatos(null, dateDesde.getDate(), dateHasta.getDate());
            Double subTotal;
            Double total = 0d;
            for (Despinches ds : datos) {
                subTotal = 0d;
                HistorialDespinchesDetalle det = new HistorialDespinchesDetalle();
                det.setCodigo(ds.getIdNeumaticos().getCodigo());
                det.setFecha(GUIUtil.convertirFechaDDMMYYY(ds.getFecha()));
                det.setKilometraje("" + ds.getKmVehiculo());
                List<DetalleDespinche> detalle = ds.getDetalleDespincheList();
                List<String[]> strDetales = new ArrayList<String[]>();
                for (DetalleDespinche detalleDespinche : detalle) {
                    String[] registro = new String[5];
                    registro[0] = detalleDespinche.getIdInsumosDespinche().getNombre();
                    registro[1] = "" + detalleDespinche.getIdInsumosDespinche().getCodigo();
                    registro[2] = "" + detalleDespinche.getCantidad();
                    registro[3] = GUIUtil.formatearNumero(detalleDespinche.getCostoUnitario());
                    registro[4] = GUIUtil.formatearNumero(detalleDespinche.getCostoTotal());
                    subTotal += detalleDespinche.getCostoTotal();
                    strDetales.add(registro);
                }
                det.setSubtotal(subTotal);
                det.setDetalles(strDetales);
                detallesHistorial.add(det);
                total += subTotal;
            }
            historial.setDetalles(detallesHistorial);
            historial.setTotal(total);
            try {
                Impresor impresor = new Impresor(historial);
                Principal.getInstance().getEscritorio().add(impresor);
                impresor.setVisible(true);
                impresor.setMaximum(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (!txtCodigo.getText().isEmpty()) {
            try {
                Query q = JPAUtil.getEntityManagerFactory().createEntityManager().createNamedQuery("Neumaticos.findByCodigo");
                q.setParameter("codigo", txtCodigo.getText().trim());
                List<Neumaticos> neumatico = q.getResultList();
                if (neumatico.size() > 0) {
                    ReporteDespinches reporte = new ReporteDespinches();
                    reporte.generarReporte(neumatico.get(0), dateDesde.getDate(), dateHasta.getDate());
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(Principal.getInstance(), "Ingrese el código de un neumático", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnDespinchesActionPerformed

private void radBtnEspecificoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radBtnEspecificoActionPerformed
// TODO add your handling code here:
//    if (!radBtnEspecifico.isSelected()) {
    txtCodigo.setText("");
    txtCodigo.setEditable(radBtnEspecifico.isSelected());
    if (radBtnEspecifico.isSelected()) {
        txtCodigo.requestFocusInWindow();
    }
//    } else {
//        txtCodigo.setEditable(true);
//    }
}//GEN-LAST:event_radBtnEspecificoActionPerformed

private void dateDesdePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateDesdePropertyChange
// TODO add your handling code here:
    if (evt.getPropertyName().compareTo("date") == 0) {
        dateHasta.setMinSelectableDate(dateDesde.getDate());
    }
}//GEN-LAST:event_dateDesdePropertyChange

private void radBtnTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radBtnTodosActionPerformed
// TODO add your handling code here:
    txtCodigo.setText("");
    txtCodigo.setEditable(!radBtnTodos.isSelected());
}//GEN-LAST:event_radBtnTodosActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDespinches;
    private javax.swing.ButtonGroup buttonGroup1;
    private com.toedter.calendar.JDateChooser dateDesde;
    private com.toedter.calendar.JDateChooser dateHasta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JRadioButton radBtnEspecifico;
    private javax.swing.JRadioButton radBtnTodos;
    private javax.swing.JTextField txtCodigo;
    // End of variables declaration//GEN-END:variables
}
